import matplotlib.pyplot as plt
import numpy as np

# ==================== 初始化设置 ====================
plt.style.use('ggplot')  # 使用更通用的专业样式
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  # 中文字体
plt.rcParams['axes.unicode_minus'] = False

# ==================== 数据准备 ====================
scenarios = ["瞬时高峰", "持续泄漏", "频繁抖动", "核心故障"]
categories = ["严重程度", "持续时间", "发生频率", "业务影响", "影响范围"]  # 添加缺失的定义

old_scores = [6.2, 5.8, 7.1, 6.9]
new_scores = [5.5, 6.3, 5.0, 8.4]
improvement = ["↓0.7", "↑0.5", "↓2.1", "↑1.5"]  # 文字标注变化方向

# ==================== 创建组合图表 ====================
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10),
                        gridspec_kw={'height_ratios': [1, 2]})

# -------------------- 面板1：权重配置对比 --------------------
weights = {
    '原权重': [25, 20, 20, 25, 10],
    '新权重': [25, 20, 15, 30, 10]
}
x = np.arange(len(categories))  # 使用已定义的categories
ax1.bar(x - 0.2, weights['原权重'], 0.4, label='原方案', color='#FF9AA2')
ax1.bar(x + 0.2, weights['新权重'], 0.4, label='优化方案', color='#A2E1DB')

ax1.set_title('权重配置优化对比', pad=20, fontsize=14)
ax1.set_xticks(x)
ax1.set_xticklabels(categories)
ax1.legend()
ax1.grid(axis='y', linestyle='--', alpha=0.3)

# -------------------- 面板2：评分效果对比 --------------------
bar_width = 0.35
x = np.arange(len(scenarios))
bars1 = ax2.bar(x - bar_width/2, old_scores, bar_width,
               color='#FF9AA2', label='原方案')
bars2 = ax2.bar(x + bar_width/2, new_scores, bar_width,
               color='#A2E1DB', label='优化方案')

# 添加数据标签
def add_labels(bars):
    for bar in bars:
        height = bar.get_height()
        ax2.annotate(f'{height:.1f}',
                    xy=(bar.get_x() + bar.get_width()/2, height),
                    xytext=(0, 3),
                    textcoords="offset points",
                    ha='center', va='bottom')

add_labels(bars1)
add_labels(bars2)

# 添加变化箭头标注
for i, (old, new) in enumerate(zip(old_scores, new_scores)):
    if new > old:
        ax2.annotate(improvement[i],
                    xy=(i, new + 0.2),
                    ha='center', color='green', fontsize=12,
                    bbox=dict(boxstyle='round,pad=0.2', fc='#E6FFE6', ec='green'))
    else:
        ax2.annotate(improvement[i],
                    xy=(i, old + 0.2),
                    ha='center', color='red', fontsize=12,
                    bbox=dict(boxstyle='round,pad=0.2', fc='#FFE6E6', ec='red'))

# 装饰性元素
ax2.set_title('异常场景评分对比', pad=16, fontsize=14, y=0.96)
ax2.set_ylabel('综合评分（10分制）', fontsize=12)
ax2.set_xticks(x)
ax2.set_xticklabels(scenarios)
ax2.set_ylim(0, 9.5)
ax2.axhline(y=8, color='red', linestyle='--', alpha=0.7, label='紧急阈值')
ax2.axhline(y=5, color='orange', linestyle=':', alpha=0.7, label='观察阈值')
ax2.grid(axis='y', linestyle='--', alpha=0.3)
ax2.legend(loc='upper right')

# 整体标题
plt.suptitle('异常检测系统优化效果分析                                                                                                                                          ', fontsize=20, y=0.96)
plt.tight_layout()
plt.savefig('optimization_impact.png', dpi=300, bbox_inches='tight')
plt.show()